<template>
	<view class="wrapper">
		<view class="main-wrapper">
			<scroll-view scroll-y class="left-menus">
				<template v-if="loading">
					<skeletonTag />
				</template>
				<template v-else>
					<view :class="item.typeId === currentTag ? 'menu-item checked' : 'menu-item'"
						v-for="item in tagList" :key="item.typeId" @tap.stop="tagChange(item)">
						<text class="txt">{{ item.typeName }}</text>
					</view>
				</template>
			</scroll-view>
			<view class="right-wrapper">
				<scroll-view scroll-y class="right-list" @scroll="scrollFunc">
					<view class="scorll-list">
						<template v-if="list && list.length > 0">
							<view class="product-box" v-for="product in list" :key="product.id">
								<FddProductItem :value="selected[product.id] ? selected[product.id].nums : 0"
									:item="product" :step="product.numMin || 1" @onChange="$event => productChange(product, $event)" />
							</view>
						</template>
						<template v-else-if="loading">
							<SkeletonProduct />
						</template>
						<template v-else>
							<xl-empty className="no-padding" empty-text="暂无商品" />
						</template>
					</view>
					<view class="fix-box"></view>
					<view class="service-btn-wrapper">
						<FddService :sendMessagePath="'/pages/orders/index'" />
					</view>
				</scroll-view>
			</view>
		</view>
		<view class="footer">
			<view class="content">
				<view class="left">
					<view class="desc">合计: </view>
					<view class="price">¥ {{ amount }}</view>
				</view>
				<view v-if="login" @tap="verifyData" class="btn">
					<image src="https://zcgoods-1322033577.cos.ap-chengdu.myqcloud.com/zcgoods%2Flb.gif"></image>
					<text class="text">支付(享免单)</text>
				</view>
			</view>
		</view>
		
		<!--免单弹框-->
		<uni-popup ref="popupRef">
			<view class="pay_success">
				<image class="success_img" lazy-load :src="mdcgImg"></image>
				<view class="pay_bg">
					<view class="tips">
						<view class="tips_success">恭喜获得免单啦！</view>
						<view class="tips_sm">退出此单今日将无法再次免单</view>
					</view>
					<view class="btn" @tap="placeOrder">去支付(仅需支付{{ freeAmount }}元)</view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>
<script setup>
	import {
		ref,
		watch
	} from "vue";
	import {
		onLoad,
		onShow, onShareAppMessage, onShareTimeline
	} from "@dcloudio/uni-app";
	import {
		setStorage,
		getStorage
	} from "@/common/storage";
	import {
		showToast,
		isLogin,
		getWeiXinCode,
		wxLogin,
		todayIsLogin
	} from "@/common/util";
	import skeletonTag from "@/skeleton/skeleton-tag.vue";
	import FddProductItem from "@/components/fdd-product-item.vue";
	import xlEmpty from "@/components/xl-empty.vue";
	import SkeletonProduct from "@/skeleton/skeleton-product.vue"
	import dayjs from "dayjs";
	import mdcgImg from "../../static/icons/mdcg.png";
	import FddService from "@/components/fdd-service.vue";
	
	const molds = 2; // 1: 非预定， 2：预定
	const containerId = ref("");
	// tag
	const tagList = ref([]);
	const loading = ref(true);
	const currentTag = ref("");
	// main
	const list = ref([]);
	const login = ref(isLogin());
	// 选中的商品
	const selected = ref({});

	const freeInfo = ref(null);
	const isFree = ref(false);
	const popupRef = ref()

	const userInfo = ref({});

	// 
	const amount = ref(0);
	const freeAmount = ref(0);

	// 查询
	const search = async () => {
		loading.value = true;
		try {
			const data = await uni.$request.get(uni.$api.commodityPage, {
				data: {
					molds,
					containerId: containerId.value, // 货柜ID
				}
			});
			loading.value = false;
			tagList.value = data || [];
			if (tagList.value.length > 0) {
				currentTag.value = tagList.value[0].typeId;
				list.value = tagList.value[0].commodities || [];
			}
		} catch (error) {
			loading.value = false;
			console.error("error:", error);
		}
	}
	// 获取用户信息
	const fetchUserInfo = async () => {
		try {
			const data = await uni.$request.get(uni.$api.customerInfo);
			const result = data || {};
			userInfo.value = result;
			if (result?.isFree && result.frees && (result.frees.containerId === containerId.value)) {
				freeInfo.value = result.frees;
				isFree.value = !!result.isFree;
			} else {
				freeInfo.value = null;
				isFree.value = false;
			}
		} catch (error) {
			loading.value = false;
			console.error("error:", error);
		}
	}

	const scrollFunc = () => {

	}
	// 切换分类
	const tagChange = (tag) => {
		currentTag.value = tag.typeId;
		const curr = tagList.value.find(v => v.typeId === tag.typeId) || {};
		list.value = curr.commodities || [];
	}

	// 商品选择
	const productChange = (product, value) => {
		selected.value[product.id] = {
			...product,
			nums: value
		};
	}

	/** 
	// 总计
	const amount = computed(() => {
		return Number(Object.keys(selected.value).reduce((p, v) => {
			if (selected.value[v]) {
				const curr = selected.value[v];
				return p + (+(curr.reductions || curr.price) * +curr.nums)
			}
			return p;
		}, 0)).toFixed(2);
	});
	// 免单后金额
	const freeAmount = computed(() => {
		console.log("selected.value", selected.value);
		return selected.value;
		if (!isFree.value || !freeInfo.value || !freeInfo.value?.otherPrice) {
			return amount.value;
		}
		debugger;
		return +amount.value < +freeInfo.value.withinPrice ? +freeInfo.value?.otherPrice : +amount.value - (+freeInfo.value?.withinPrice) + (+freeInfo.value?.otherPrice);
	})

	*/

	const resetData = () => {
		popupRef.value.close();
		selected.value = {};
	}

	// 拼接参数
	const getParams = () => {
		let totals = 0;
		const commodities = [];
		Object.keys(selected.value).forEach(v => {
			if (selected.value[v] && selected.value[v].nums > 0) {
				const curr = selected.value[v];
				commodities.push({
					"commodityId": curr.id,
					"discounteds": +Number(curr.reductions * curr.nums).toFixed(2),
					"nums": curr.nums,
					"price": curr.price,
					"totals": +Number(curr.price * curr.nums).toFixed(2)
				});
				totals += (+curr.price * curr.nums);
			}
		})
		if (isFree.value && freeInfo.value) {
			return {
				totals,
				commodities,
				containerId: containerId.value,
				molds,
				discounteds: freeAmount.value
			}
		}
		return {
			totals,
			commodities,
			containerId: containerId.value,
			molds,
			discounteds: amount.value
		}
	}
	// 支付订单
	const payOrder = (data = {}) => {
		wx.requestPayment({
			appId: data.appId,
			timeStamp: data.timeStamp,
			nonceStr: data.nonceStr,
			package: data.packageVal,
			signType: data.signType,
			paySign: data.paySign,
			success: () => {
				resetData();
				uni.navigateTo({
					url: "/pages/orders/success?molds=2"
				});
			},
			fail: (error) => {
				console.log('error', error);
				showToast("支付失败!");
			}
		})
	}
	// 下单
	const placeOrder = async () => {
		const params = getParams();
		try {
			const data = await uni.$request.post(uni.$api.orderNewly, {
				isLoading: true,
				data: params
			});
			if (data.pays) {
				payOrder(data.pays);
				fetchUserInfo();
			}
		} catch (error) {
			console.error("error:", error);
		}
	}
	// 校验商品
	const verifyData = () => {
		let nums = 0;
		Object.keys(selected.value).forEach((key) => {
			if (selected.value[key]) {
				nums += (selected.value[key].nums || 0);
			}
		});
		if (!(nums > 0)) {
			showToast("请选择商品");
			return;
		}
		if (isLogin()) {
			if (isFree.value) {
				// 如果免单弹框
				popupRef.value.open();
			} else {
				placeOrder();
			}
		} else {
			getWeiXinCode((code) => {
				wxLogin(code, {containerId: containerId.value}).then((tokenObj) => {
					setStorage("token", tokenObj.tokenValue);
					login.value = true;
					if (isFree.value) {
						// 如果免单弹框
						popupRef.value.open()
					} else {
						placeOrder();
					}
				});
			});
		}
	}

	onShareAppMessage (() => {
		return {
      title: '点餐就免单！不玩套路！',
      path: `/pages/orders/index?userId=${userInfo.id}&containerId=${containerId.value}`
    }
	});
	onShareTimeline (() => {
		return {
      title: '点餐就免单！不玩套路！',
      path: `/pages/orders/index?userId=${userInfo.id}&containerId=${containerId.value}`
    }
	});

	watch(() => JSON.stringify(selected.value), () => {
		// 是否选中商品
		if (!Object.keys(selected.value) || !Object.keys(selected.value).length) {
			amount.value = 0;
			freeAmount.value = 0;
		}
		// 总金额
		let amountValue = 0;
		// 免单商品金额
		let freeAmountValue = 0;
		// 非免单商品金额
		let notFreeAmountValue = 0;
		Object.keys(selected.value).forEach(v => {
			if (selected.value[v]) {
				const curr = selected.value[v];
				// 当前商品的金额
				const currAmount = (+(curr.reductions || curr.price) * +curr.nums);
				amountValue += currAmount;
				// 商品是否免单
				if (+curr.isFrees === 1) {
					freeAmountValue += currAmount;
				} else {
					notFreeAmountValue += currAmount;
				}
			}
		})
		amount.value = Number(amountValue.toFixed(2));
		// 判断是否有免单资格，没有免单资格直接取总金额
		if (!isFree.value || !freeInfo.value || !freeInfo.value?.otherPrice) {
			freeAmount.value = Number(amountValue.toFixed(2));
		} else {
			// 如果免单商品总金额小于免单额度。则取免单额度内的免单金额，否则取免单额度内的免单金额 + 免单额度外的金额
			const freeValue = freeAmountValue < +freeInfo.value.withinPrice ? +freeInfo.value?.otherPrice : +freeAmountValue - (+freeInfo.value?.withinPrice) + (+freeInfo.value?.otherPrice);
			// 拿用户选中的商品金额和免单金额对比。如何小于免单额度内的金额则直接取客户的商品金额。 最后加上非免单商品的金额
			freeAmount.value = Number(((freeAmountValue < freeValue ? freeAmountValue : freeValue) + notFreeAmountValue).toFixed(2));
		}
	})
	onShow(() => {
		if (containerId.value) {
			search();
		}
		if (!todayIsLogin()) {
			getWeiXinCode((code) => {
				wxLogin(code, {containerId: containerId.value}).then((tokenObj) => {
					setStorage("token", tokenObj.tokenValue);
					setStorage("lastLoginTime", dayjs(new Date()).format("YYYY-MM-DD"));
					login.value = true;
					fetchUserInfo();
				});
			});
		} else {
			fetchUserInfo();
		}
	})
	onLoad((options) => {
		// || "480080634565061"
		const id = options.containerId || getStorage("containerId") || "480080634565061"
		if (id) {
			setStorage("containerId", id);
			containerId.value = id;
		}
	});
</script>
<style lang="scss" scoped>
	.wrapper {
		width: 100%;
		height: 100vh;

		.main-wrapper {
			height: calc(100vh - 124upx);
			display: flex;
			justify-content: flex-start;
			flex-wrap: nowrap;
			box-sizing: border-box;

			.left-menus {
				width: 166upx;
				height: 100%;
				padding-top: 30upx;
				box-sizing: border-box;

				.menu-item {
					width: 100%;
					height: 66upx;
					box-sizing: border-box;
					display: flex;
					justify-content: flex-start;
					align-items: center;
					padding-left: 30upx;
					margin-top: 16upx;

					&:first-child {
						margin-top: 0;
					}

					.txt {
						color: #30302F;
						font-size: 30upx;
						font-style: normal;
						font-weight: 400;
						line-height: normal;
						white-space: nowrap;
						overflow: hidden;
						text-overflow: ellipsis;
					}

					&.checked {
						border-radius: 0px 100upx 100upx 0px;
						background: #E5E5E5;

						.txt {
							color: #30302F;
							font-size: 30upx;
							font-style: normal;
							font-weight: bold;
							line-height: normal;
						}
					}
				}
			}

			.right-wrapper {
				margin-left: 24upx;
				flex: 1;
				height: 100%;
				box-sizing: border-box;

				.right-list {
					width: 100%;
					height: 100%;
					padding-top: 20upx;
					box-sizing: border-box;

					.scorll-list {
						border-radius: 23upx;
						background: #FFF;
						padding: 30upx;
						padding-right: 24upx;
						box-sizing: border-box;

						.product-box {
							padding-top: 30upx;
							padding-bottom: 30upx;
							border-top: 1upx solid #dbdbdb;

							&:first-child {
								padding-top: 0;
								border-top: none;
							}

							&:last-child {
								padding-bottom: 0;
							}
						}
					}

					.fix-box {
						width: 100%;
						height: 30upx;
					}
					.service-btn-wrapper {
						position: fixed;
						right: 0;
						bottom: 280upx;
						width: 100upx;
						height: 100upx;
						z-index: 1;
					}
				}
			}
		}

		.footer {
			width: 100%;
			height: 124upx;
			box-sizing: border-box;
			padding: 16upx 0;
			background-color: #FFF;

			.content {
				width: 690upx;
				margin-left: auto;
				margin-right: auto;
				display: flex;
				justify-content: space-between;
				align-items: center;

				.left {
					display: flex;
					justify-content: flex-start;
					align-items: center;

					.desc {
						color: #1F1F1F;
						font-size: 30upx;
						font-style: normal;
						font-weight: 500;
						line-height: normal;
					}

					.price {
						color: #FF4D56;
						font-size: 38upx;
						font-style: normal;
						font-weight: 700;
						line-height: normal;
						margin-left: 30upx;
					}
				}

				.btn {
					padding-left: 16upx;
					padding-right: 16upx;
					height: 100upx;
					border-radius: 100upx;
					background: #FF4D56;
					margin: 0;
					color: #FFF;
					font-size: 30upx;
					font-style: normal;
					font-weight: 600;
					text-align: center;
					display: flex;
					align-items: center;
					justify-content: center;

					image {
						width: 100rpx;
						height: 140rpx;
						transform: translateY(-10px);
					}
				}
			}
		}
	}

	.pay_success {
		width: 690upx;
		height: 500upx;
		position: relative;
		
		.success_img {
			position: absolute;
			z-index: 33;
			width: 300rpx;
			height: 300rpx;
			margin: auto;
			left: 0;
			right: 0;
			bottom: 0;
			top: -200rpx;
			background-color: transparent;
		}
		.pay_bg {
			position: absolute;
			z-index: 22;
			height: 30vh;
			width: 80%;
			top: 200rpx;
			margin: auto;
			left: 10%;
			border-radius: 20rpx;
			background: linear-gradient(red, white);
			display: flex;
			justify-content: center;
			flex-wrap: wrap;
		}
		.tips {
			width: 100%;
			color: yellow;
			margin-top: 100rpx;
			text-align: center;
			
			.tips_sm {
				font-size: 22rpx;
			}
		}
		.btn {
			padding-left: 16upx;
			padding-right: 16upx;
			height: 100upx;
			border-radius: 100upx;
			background: #FF4D56;
			margin: 0;
			color: #FFF;
			font-size: 30upx;
			font-style: normal;
			font-weight: 600;
			text-align: center;
			display: flex;
			align-items: center;
			justify-content: center;
			width: 400rpx;
		}
	}
</style>